//
//  UITableView.swift
//  TCCKit
//
//  Created by tucici on 2023/3/4.
//

import UIKit

@objc public extension UITableView{
    
    //MARK: - cell右滑时，设置cell的删除按钮为圆角，且cell的右边能遮挡cell的左边的圆角，使删除按钮与cell之间没有空洞的地方
    /// cell右滑时，设置cell的删除按钮为圆角，且cell的右边能遮挡cell的左边的圆角，使删除按钮与cell之间没有空洞的地方
    ///  在delegate的 tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath)方法中调用此方法
    /// - Parameter bgcolor: 删除按钮的背景颜色
    func cellDelBtnRadius(_ bgcolor:UIColor){
        var deleteBtn : UIButton?
        if #available(iOS 11.0, *) {  //  适配iOS 11.0之后 修改侧滑删除、分享按钮
            for subView in self.subviews {
                if NSStringFromClass(subView.classForCoder) == "UISwipeActionPullView" {
                    if let btn: UIButton = subView.subviews.last as? UIButton  {
                        deleteBtn = btn
                    }
                }
                // iOS13.0之后
                else if NSStringFromClass(subView.classForCoder) == "_UITableViewCellSwipeContainerView" {
                    for sub in subView.subviews {
                        if NSStringFromClass(sub.classForCoder) == "UISwipeActionPullView" {
                            if let btn: UIButton = sub.subviews.last as? UIButton  {
                                deleteBtn = btn
                            }
                        }
                    }
                }
            }
            
            if (deleteBtn ?? nil) == nil{return}
            
            ///用整个cell的宽度，和删除按钮的高度，定制绘画layer的区域
            let b = CGRect(x: 0, y: 0, width:self.bounds.width - 20, height: deleteBtn!.bounds.height)
            let path = UIBezierPath(roundedRect:b, byRoundingCorners: [.topLeft,.topRight,.bottomLeft,.bottomRight], cornerRadii: CGSize(width: 10, height: 10))
            let layer = CAShapeLayer()
            ///此句非常重要，系统的删除按钮宽度是70，把layer的x起点设置成负数，可以让cell的圆角遮住删除按钮左边的圆角
            layer.frame = CGRect(x:-self.bounds.width + 90, y: 0, width: b.width, height: b.height)
            layer.path = path.cgPath
            layer.fillColor = bgcolor.cgColor
            
            deleteBtn?.layer.addSublayer(layer)
            if deleteBtn?.imageView != nil{
                deleteBtn?.bringSubviewToFront(deleteBtn!.imageView!)
            }
            if deleteBtn?.titleLabel != nil{
                deleteBtn?.bringSubviewToFront(deleteBtn!.titleLabel!)
            }
        }
    }
}
